package com.hoshiicloud.user.service.impl.visitors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.user.entity.visitors.Visitors;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.visitors.VisitorsMapper;
import com.hoshiicloud.user.service.visitors.IVisitorsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author:campchen
 * @Date:Created in 下午 02:24 2019/9/10
 * @PACKAGENAME com.hoshiicloud.user.service.impl.visitors
 * @Description
 */
@Service
public class VisitorsServiceImpl extends ServiceImpl<VisitorsMapper, Visitors> implements IVisitorsService {
    @Autowired
    private IdGeneratorService idGeneratorService;

    @Override
    @Cacheable(cacheNames = "Visitors",key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    public Visitors getById(Long id) {
        return baseMapper.selectById(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Visitors", allEntries = true)
    public String insert(Visitors entity) {
        String id = idGeneratorService.queryGeneratorId();
        int row = baseMapper.insert(entity);
        if (row < 0) {
            throw new ServiceException(CommonError.error("访客记录新增失败"));
        }
        return id;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Visitors", allEntries = true)
    public boolean deleteById(long id) {
        int row = baseMapper.deleteById(id);
        if (row < 0) {
            throw new ServiceException(CommonError.error("访客记录删除失败"));
        }
        return true;
    }


    @Override
    @Cacheable(cacheNames = "Visitors", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public IPage<Visitors> getPage(IPage<Visitors> page, QueryWrapper<Visitors> queryWrapper, String key) {
        return baseMapper.selectPage(page,queryWrapper);
    }

    /**
     * 批量查询访客数信息
     */
    @Override
    public List<Visitors> queryBatch(List<OmnipotentWrapper> param) {
        QueryWrapper<Visitors> wrapper = new OmnipotentWrapper<Visitors>().getWrapper(param);
        List<Visitors> visitors = baseMapper.selectList(wrapper);
        return visitors;
    }
}

